// TriCon.java - Alexander Shabarshin  08-Feb-2006
// See http://ternary.info

import java.applet.*;
import java.awt.*;

public class TriCon extends Applet
{
 TextField text2;
 TextField text3;
 TextField text10;
 TextField text16;
 int number;

 public void init()
 {
  setLayout(new GridLayout(4,2));
  add(new Label("Ternary (N,O,P):"));
  text3 = new TextField(24);
  add(text3);
  add(new Label("Decimal (0-9):"));
  text10 = new TextField(16);
  add(text10);
  add(new Label("Hexadecimal (0-9,A-F):"));
  text16 = new TextField(8);
  add(text16);
  add(new Label("Binary (0,1):"));
  text2 = new TextField(32);
  add(text2);
 }

 public boolean action(Event event, Object object)
 {
  if(text2.equals((TextField)event.target))
  {
    number = Integer.parseInt(text2.getText(),2);
    text3.setText(toTernary(number));
    text10.setText(Integer.toString(number));
    text16.setText(Integer.toHexString(number).toUpperCase());
  }
  if(text3.equals((TextField)event.target))
  {
    number = fromTernary(text3.getText());
    text2.setText(Integer.toBinaryString(number));
    text10.setText(Integer.toString(number));
    text16.setText(Integer.toHexString(number).toUpperCase());
  }
  if(text10.equals((TextField)event.target))
  {
    number = Integer.parseInt(text10.getText(),10);
    text2.setText(Integer.toBinaryString(number));
    text3.setText(toTernary(number));
    text16.setText(Integer.toHexString(number).toUpperCase());
  }
  if(text16.equals((TextField)event.target))
  {
    number = Integer.parseInt(text16.getText(),16);
    text2.setText(Integer.toBinaryString(number));
    text3.setText(toTernary(number));
    text10.setText(Integer.toString(number));
  }
  return true;
 }

 public static String toTernary(int num)
 {
    int n,m,k;
    String s = null;
    k = 387420489;
    for(int i=0;i<=18;i++)
    {
      n = num/k;
      num -= n*k;
      m = k/2;
      if(num>+m){n++;num-=k;}
      if(num<-m){n--;num+=k;}
      if(n!=0 && s==null) s="";
      if(n==-1) s+="N";
      if(n==0 && s!=null) s+="O";
      if(n==1) s+="P";
      k /= 3;
    } 
    return s;
 }
 
 public static int fromTernary(String s)
 {
    int n = 0;
    int k = 1;
    for(int i=s.length()-1;i>=0;i--)
    {
      char c = s.charAt(i);
      if(c!='N'&&c!='O'&&c!='P') return 0;
      if(c=='N') n-=k;
      if(c=='P') n+=k;
      k *= 3;
    }
    return n;
 }

}
